﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using OutlookPanel;
using System.Runtime.InteropServices;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace SNAIL
{
    public partial class ThisAddIn
    {
        private Outlook.Explorer _outlookExplorer;

        /// <summary>
        /// Custom panel instance
        /// </summary>
        private MyPanel _customPanel;

        /// <summary>
        /// Called when user selected an item (in Inbox, Contacts, etc.)
        /// </summary>
        private void outlookExplorer_SelectionChange()
        {
            if (_outlookExplorer.Selection.Count == 0)
                return; //No selection has been made

            //Take the first selected item 
            Outlook.MailItem mailItem = _outlookExplorer.Selection[1] as Outlook.MailItem;


        }

        /// <summary>
        /// Name of Outlook process
        /// </summary>
        private const string OUTLOOK_PROCESS_NAME = "outlook";

        /// <summary>
        /// Window class used to identify the sibling window
        /// </summary>
        private const string SIBLING_WINDOW_CLASS = "rctrl_renwnd32";


        /// <summary>
        /// Find Outlook window
        /// </summary>
        /// <returns></returns>
        private static IntPtr FindOutlookWindow()
        {
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(OUTLOOK_PROCESS_NAME);

            if (processes == null || processes.Length == 0)
                return IntPtr.Zero;

            return processes[0].MainWindowHandle;
        }

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            if (this.Application == null)
                return; //We were not loaded into Outlook, so do nothing

            //Get the instance of Outlook active explorer (= the main window) and start capturing selection changes
            _outlookExplorer = this.Application.ActiveExplorer();
            _outlookExplorer.SelectionChange += new Outlook.ExplorerEvents_10_SelectionChangeEventHandler(outlookExplorer_SelectionChange);

            RemoveMenubar();
            AddMenuBar();

            //Find Outlook window handle (HWND)

            IntPtr outlookWindow = FindOutlookWindow();
            if (outlookWindow == IntPtr.Zero)
                return;

            //Find sibling window handle (HWND)
            //Sibling window is the window which we are going to "cut" to make space for our own window
            IntPtr siblingWindow = SafeNativeMethods.FindWindowEx(outlookWindow, IntPtr.Zero, SIBLING_WINDOW_CLASS, null);
            if (siblingWindow == IntPtr.Zero)
                return;

            //Initialise PanelManager and assign own panel to it
            _panelManager = new PanelManager(outlookWindow, siblingWindow);
            _customPanel = new MyPanel(this.Application);
            _panelManager.ShowBarControl(_customPanel);
        }

        private Office.CommandBar menuBar;
        private Office.CommandBarPopup newMenuBar;
        private Office.CommandBarButton InfoButton;
        private Office.CommandBarButton SocialButton;
        private Office.CommandBarButton SettingsButton;
        private Office.CommandBarButton HideShowButton;

        private string menuTag = "WorldAddIn";

        private void AddMenuBar()
        {
            try
            {
                //Define the existent Menu Bar
                menuBar = this.Application.ActiveExplorer().CommandBars.ActiveMenuBar;
                //Define the new Menu Bar into the old menu bar
                newMenuBar = (Office.CommandBarPopup)menuBar.Controls.Add(
                    Office.MsoControlType.msoControlPopup, missing,
                    missing, missing, false);
                //If I dont find the newMenuBar, I add it
                if (newMenuBar != null)
                {
                    newMenuBar.Caption = "SNAIL";
                    newMenuBar.Tag = menuTag;
                    InfoButton = (Office.CommandBarButton)newMenuBar.Controls.
                    Add(Office.MsoControlType.msoControlButton, missing,
                        missing, 1, true);
                    InfoButton.Style = Office.MsoButtonStyle.
                        msoButtonIconAndCaption;
                    InfoButton.Caption = "About SNAIL";
                    //This is the Icon near the Text
                    InfoButton.FaceId = 610;
                    InfoButton.Tag = "c123";
                    InfoButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(InfoButton_Click);

                    SocialButton = (Office.CommandBarButton)newMenuBar.Controls.
                    Add(Office.MsoControlType.msoControlButton, missing,
                        missing, 1, true);
                    SocialButton.Style = Office.MsoButtonStyle.
                        msoButtonIconAndCaption;
                    SocialButton.Caption = "Show Social Graph";
                    //This is the Icon near the Text
                    SocialButton.FaceId = 610;
                    SocialButton.Tag = "c124";
                    SocialButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(SocialButton_Click);

                    SettingsButton = (Office.CommandBarButton)newMenuBar.Controls.
                    Add(Office.MsoControlType.msoControlButton, missing,
                        missing, 1, true);
                    SettingsButton.Style = Office.MsoButtonStyle.
                        msoButtonIconAndCaption;
                    SettingsButton.Caption = "Settings";
                    //This is the Icon near the Text
                    SettingsButton.FaceId = 610;
                    SettingsButton.Tag = "c125";
                    SettingsButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(SettingsButton_Click);

                    HideShowButton = (Office.CommandBarButton)newMenuBar.Controls.
                    Add(Office.MsoControlType.msoControlButton, missing,
                        missing, 1, true);
                    HideShowButton.Style = Office.MsoButtonStyle.
                        msoButtonIconAndCaption;
                    HideShowButton.Caption = "Toggle SNAIL";
                    //This is the Icon near the Text
                    HideShowButton.FaceId = 610;
                    HideShowButton.Tag = "c126";
                    HideShowButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(HideShowButton_Click);

                    newMenuBar.Visible = true;
                }
            }
            catch (Exception ex)
            {
            }
        }

        void HideShowButton_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
        {
            _panelManager.ToggleBarControl();
        }

        void SettingsButton_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
        {
            SNAIL.Interfaces.Settings newsettingswindows = new SNAIL.Interfaces.Settings(_customPanel.SortSetting, _customPanel.DaysForCorrelation);
            newsettingswindows.ShowDialog();
            _customPanel.SortSetting = newsettingswindows.SetSetting;
            _customPanel.DaysForCorrelation = newsettingswindows.DaysForCorrelation;
            _customPanel.RefreshList();
        }

        void SocialButton_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
        {
            SNAIL.Interfaces.SocialGraph newgraphwindow = new SNAIL.Interfaces.SocialGraph(_customPanel.Contacts);
            newgraphwindow.Show();
        }

        void InfoButton_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
        {
            AboutSNAIL infobox = new AboutSNAIL();
            infobox.ShowDialog();
        }

        private void RemoveMenubar()
        {
            // If the menu already exists, remove it.
            try
            {
                Office.CommandBarPopup foundMenu = (Office.CommandBarPopup)
                    this.Application.ActiveExplorer().CommandBars.ActiveMenuBar.
                    FindControl(Office.MsoControlType.msoControlPopup,
                    missing, menuTag, true, true);
                if (foundMenu != null)
                {
                    foundMenu.Delete(true);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Panel manager instance
        /// </summary>
        private PanelManager _panelManager;

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.Combine("SNAIL", "SNAIL_DICT.dict"));

            Stream stream = File.Open(fileName, FileMode.Create);
            BinaryFormatter bFormatter = new BinaryFormatter();
            bFormatter.Serialize(stream, _customPanel.FromToMessages);
            stream.Close();
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}
